package com;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.transfer.Transfer;
import com.amazonaws.services.s3.transfer.TransferProgress;
import org.apache.commons.logging.LogFactory;

public class XferMgrProgress {

    // waits for the transfer to complete, catching any exceptions that occur.
    public static void waitForCompletion(Transfer xfer) {
        try {
            xfer.waitForCompletion();
        } catch (AmazonServiceException e) {
            LogFactory.getLog(XferMgrProgress.class).error("Amazon service error: ", e);
            System.exit(1);
        } catch (AmazonClientException e) {
            LogFactory.getLog(XferMgrProgress.class).error("Amazon client error: ", e);
            System.exit(1);
        } catch (InterruptedException e) {
            LogFactory.getLog(XferMgrProgress.class).error("Transfer interrupted: ", e);
            System.exit(1);
        }
    }

    // Prints progress while waiting for the transfer to finish.
    public static void showTransferProgress(Transfer xfer) {
        // print the transfer's human-readable description
        System.out.println(xfer.getDescription());
        do {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                LogFactory.getLog(XferMgrProgress.class).error(null, e);
                return;
            }
            // Note: so_far and total aren't used, they're just for
            // documentation purposes.
            TransferProgress progress = xfer.getProgress();
            long so_far = progress.getBytesTransferred();
            long total = progress.getTotalBytesToTransfer();
            double pct = progress.getPercentTransferred();
            System.out.print('\r');
            System.out.print(pct+"%");
        } while (!xfer.isDone());
        // print the final state of the transfer.
        Transfer.TransferState xfer_state = xfer.getState();
        System.out.println(" ");
        System.out.println("upload " + xfer_state);
    }



}
